package com.xbongbong.pro.dataset.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xbongbong.paas.bi.pojo.DataSetValueAnalysisPojo;
import com.xbongbong.paas.bi.pojo.dto.DataSetParseDTO;
import com.xbongbong.paas.bi.pojo.vo.DataSetResultVO;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.XbbConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.BIProductReformEnum;
import com.xbongbong.paas.enums.bi.DataSetNodeTypeEnum;
import com.xbongbong.paas.pojo.ItemDataPoJo;
import com.xbongbong.paas.pojo.vo.SearchDataInConditionVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.MD5Util;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.bi.commons.helper.CollectionHelper;
import com.xbongbong.pro.bi.commons.pojo.AggFieldPojo;
import com.xbongbong.pro.dataset.helper.RelatedProductHelper;
import com.xbongbong.pro.dataset.service.DataSetChartResultService;
import com.xbongbong.pro.dataset.service.ParseSqlService;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.StatisticsServicesErrorCodeEnum;
import com.xbongbong.pro.statistic.abstracts.AbstractChartResultBase;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.enums.DrillFieldEnum;
import com.xbongbong.pro.statistic.help.ChartResultHelp;
import com.xbongbong.pro.statistic.help.CustomHelp;
import com.xbongbong.pro.statistic.help.DataSetHelp;
import com.xbongbong.pro.statistic.pojo.ChartFieldAttrPojo;
import com.xbongbong.pro.statistic.pojo.ChartParamPojo;
import com.xbongbong.pro.statistic.pojo.SlaveSourcePojo;
import com.xbongbong.pro.statistic.result.pojo.AggsBucketsPojo;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.FieldAttrPojo;
import com.xbongbong.pro.statistic.result.pojo.dto.ChartLinkDTO;
import com.xbongbong.pro.statistic.result.pojo.dto.ChartResultDTO;
import com.xbongbong.pro.statistic.result.pojo.dto.DiyResultDTO;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartAnalysisVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultDetailVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultChartVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultTableVO;
import com.xbongbong.pro.statistic.service.ChartExportService;
import com.xbongbong.pro.statistics.enums.StatisticsSumEnum;
import com.xbongbong.pro.statistics.factory.ChartTypeAnalysisFactory;
import com.xbongbong.pro.statistics.help.CommonHelper;
import com.xbongbong.pro.statistics.help.StatisticsTableHelper;
import com.xbongbong.pro.statistics.helper.ChartDataSetHelper;
import com.xbongbong.pro.statistics.pojo.dto.ChartAnalysisDTO;
import com.xbongbong.pro.statistics.pojo.dto.GenerateSqlDTO;
import com.xbongbong.pro.statistics.pojo.vo.GenerateSqlVO;
import com.xbongbong.pro.statistics.service.StarDataService;
import com.xbongbong.pro.statistics.strategy.chart.type.ChartTypeStrategyService;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.SelectProductEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 描述信息
 *
 * @ClassName DataSetChartResultServiceImpl
 * @Author 梁鲁江
 * 创建时间 2022/9/16 10:03
 * 修改时间  2022/9/16 10:03
 **/
@Service("dataSetChartResultService")
public class DataSetChartResultServiceImpl extends AbstractChartResultBase implements DataSetChartResultService {
    @Resource
    private CommonHelper commonHelper;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private CustomHelp customHelp;
    @Resource
    private StarDataService starDataService;
    @Resource
    private StatisticsTableHelper statisticsTableHelper;
    @Resource
    private ChartResultHelp chartResultHelp;
    @Resource
    private DataSetHelp dataSetHelp;
    @Resource
    private ParseSqlService parseSqlService;
    @Resource
    private ChartDataSetHelper chartDataSetHelper;
    @Resource
    private RelatedProductHelper relatedProductHelper;
    @Resource
    private ChartExportService chartExportService;

    public Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public ChartResultVO chartResult(ChartResultDTO chartResultDTO) throws XbbException {
        return getChartResult(chartResultDTO);
    }

    @Override
    public void filterByDriverSource(ChartResultDTO chartResultDTO, ChartParamPojo chartParamPojo, ChartEntity chartEntity) throws XbbException {
        //校验数据源为数据集的图表是否需要重置
        if(dataSetHelp.resetChartByDataSet(chartResultDTO.getCorpid(),chartEntity.getDriverSources(),chartEntity.getSingle(),chartEntity.getDataSetCompareTime(),null)){
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224099, StatisticsServicesErrorCodeEnum.API_ERROR_224099.getMsg());
        }
    }

    @Override
    public ChartResultDetailVO getDiyResult(ChartEntity chartEntity, ChartResultPojo chartResultPojo, List<PaasFormExplainEntity> explainEntityList, List<JSONObject> search,boolean penetrateFlag) throws XbbException {
        ChartResultDetailVO chartResultDetailVO = new ChartResultDetailVO();
        chartResultDetailVO.setChartId(chartEntity.getId());
        chartResultDetailVO.setChartEntity(chartEntity);
        //如果是数据集，字段和explain里可能就不再对应，originalAttr多层的时候可能也不对应  TODO 暂时不处理更新解释

        //处理查询条件
        chartResultHelp.searchCheck(search,chartEntity,chartResultPojo);
        //图表使用数量的限制
        chartDataSetHelper.chartDataLimit(chartEntity.getCorpid(), chartEntity.getDriverSources(), chartEntity.getSlaveSources(),chartEntity.getSingle());
        DiyResultDTO diyResultDTO = new DiyResultDTO();
        BeanUtil.copyProperties(chartResultPojo, diyResultDTO, true);
        diyResultDTO.setChartEntity(chartEntity);
        diyResultDTO.setChartResultDetailVO(chartResultDetailVO);
        diyResultDTO.setChartResultPojo(chartResultPojo);

        //获取缓存key
        String key = chartResultHelp.getChartCacheKey(chartEntity,chartResultPojo,diyResultDTO);
        // 从缓存获取存在的数据
        String diyResponseStr = paasRedisHelper.getValue(RedisPrefixConstant.DS_CHART_RESULT, key);
        if(StringUtils.isNotBlank(diyResponseStr)){
            return JSONObject.parseObject(diyResponseStr, ChartResultDetailVO.class, Feature.OrderedField);
        }

        //获取图表数据,并设置5分钟缓存
        getResult(diyResultDTO);
        paasRedisHelper.setValue(RedisPrefixConstant.DS_CHART_RESULT, key, chartResultDetailVO, RedisTimeConstant.TINY_DURATION);
        return chartResultDetailVO;
    }

    public ChartResultDetailVO getResult(DiyResultDTO diyResultDTO) throws XbbException {
        ChartResultDetailVO chartResultDetailVO = diyResultDTO.getChartResultDetailVO();
        try {
            ChartEntity chartEntity = diyResultDTO.getChartEntity();
            SlaveSourcePojo driverSourcePojo = JSON.toJavaObject(chartEntity.getDriverSources(), SlaveSourcePojo.class);
            TransmittableThreadLocalUtil.setValue(driverSourcePojo.getSaasMark(), driverSourcePojo.getBusinessType(), driverSourcePojo.getMenuId(), null);
            JSONArray tableHead = new JSONArray();
            Map<JSONObject, FieldAttrPojo> parseAttrMap = new HashMap<>(XbbConstant.INITIALCAPACITY);
            Integer chartType = chartEntity.getChartType();
            ChartTypeStrategyService chartTypeStrategyService = ChartTypeAnalysisFactory.getChartTypeStrategyService(chartType);
            ChartResultPojo chartResultPojo = diyResultDTO.getChartResultPojo();
            // 处理不显示离职人员
            //TODO 暂时注释
//            chartResultHelp.handleLeaveNoShow(chartEntity);
            // 是否是预警脚本跑的
            Boolean isWarningSync = chartResultPojo.getIsWarningSync();
            if (Objects.isNull(isWarningSync) || !isWarningSync) {
                //表单权限
                customHelp.setPermission(chartEntity, diyResultDTO);
            }
            GenerateSqlDTO generateSqlDTO = new GenerateSqlDTO();
            generateSqlDTO.setChartEntity(chartEntity);
            generateSqlDTO.setChartResultPojo(chartResultPojo);
            generateSqlDTO.setTableHead(tableHead);
            generateSqlDTO.setParseAttrMap(parseAttrMap);
            //多表对关联表的特殊处理
//            commonHelper.biProductFliter(chartEntity, true);
            //sql的生成
            GenerateSqlVO generateSqlVO = null;
            try {
                generateSqlVO = chartTypeStrategyService.generateSql(generateSqlDTO);
            } catch (XbbException e) {
                throw e;
            } catch (Exception e) {
                logger.error("chartId===" + chartEntity.getId(), e);
                throw new XbbException(BiErrorCodeEnum.API_ERROR_241023);
            }
            StringBuffer stringBufferSql = generateSqlVO.getStringBufferSql();
            if (stringBufferSql == null || stringBufferSql.length() <= 0) {
                chartResultDetailVO.setChart(new ArrayList<>());
                return chartResultDetailVO;
            }
            String sql = stringBufferSql.toString();
            PageHelper pageHelper = generateSqlVO.getPageHelper();
            Map<String, AggFieldPojo> aggFieldMap = generateSqlVO.getAggFieldMap();
            if (commonHelper.getPrintLog(diyResultDTO.getCorpid())) {
                //操作人   图表id   
                logger.info("DS===chartId===" + chartEntity.getId() + "===SQL===" + sql);
            }
            //根据图表类型渲染结果
            ChartAnalysisDTO chartAnalysisDTO = new ChartAnalysisDTO();
            BeanUtil.copyProperties(diyResultDTO, chartAnalysisDTO, true);
            List resultList = starDataService.findListMapBySql(sql);
            //小计、总计、总计&小计数据获取
            statisticsTableTotalResult(generateSqlVO,chartAnalysisDTO,chartEntity);
            //解决[NULL]问题
            if (CollectionHelper.isNullList(resultList)){
                resultList = Lists.newArrayList();
            }
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
            //关联产品渲染处理,处理关联产品
            JSONObject boardJson = JSONObject.parseObject(generateSqlVO.getJsonStr());
            if (Objects.nonNull(boardJson) && sql.contains(StringConstant.CROSS+StringConstant.PRODUCT)) {
                String nodeId = null;
                Set<String> inputNodeIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long, String> formIdNodeIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long, DataSetValueAnalysisPojo> formIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Set<String> boardKeySet = boardJson.keySet();
                for (String node : boardKeySet) {
                    JSONObject json = boardJson.getJSONObject(node);
                    //图表中心预览，关联产品input节点没有field数组字段，需要解析fieldChecked构建formIdNodeIdMap, inputNodeIdSet参数，供handlerRelProduct方法使用
                    if(Objects.equals(json.getString(XbbConstant.TYPE), DataSetNodeTypeEnum.INPUT.getAlias())) {
                        inputNodeIdSet.add(node);
                        Long formId = json.getLong(StringConstant.FORM_ID);
                        JSONArray fieldChecked = json.getJSONArray(XbbConstant.FIELD_CHECKED);
                        Integer businessType = json.getInteger(StringConstant.BUSINESS_TYPE);
                        BIProductReformEnum biProductReformEnum = BIProductReformEnum.getEnumByProductBusinessType(businessType);
                        if (Objects.nonNull(biProductReformEnum)) {
                            formIdNodeIdMap.put(formId,node);
                            List<ChartFieldAttrPojo> fieldAttrEntities = fieldChecked.stream().filter(fieldC -> fieldC.equals(SelectProductEnum.PRODUCT.getAttr())).map(field -> {
                                ChartFieldAttrPojo chartFieldAttrPojo = new ChartFieldAttrPojo();
                                chartFieldAttrPojo.setAttr(field.toString());
                                chartFieldAttrPojo.setBusinessType(businessType);
                                chartFieldAttrPojo.setFieldType(SelectProductEnum.PRODUCT.getFieldType());
                                chartFieldAttrPojo.setFormId(formId);
                                return chartFieldAttrPojo;
                            }).collect(Collectors.toList());
                            formIdMap.put(formId,new DataSetValueAnalysisPojo(json.getInteger(StringConstant.BUSINESS_TYPE),fieldAttrEntities));
                        }
                    }else if(Objects.equals(json.getString(XbbConstant.TYPE), DataSetNodeTypeEnum.OUTPUT.getAlias())){
                        //输出节点直接去找他的input
                        nodeId  = json.getJSONArray(DataSetNodeTypeEnum.INPUT.getAlias()).getString(0);
                    }
                }
                //解决关联产品渲染问题
                Map<Long,String> attrRelationProduct = Maps.newHashMap();
                JSONObject node = boardJson.getJSONObject(nodeId);
                JSONArray fieldArray = node.getJSONArray(XbbConstant.DS_FIELD);
                int fieldSize = fieldArray.size();
                for (int i = 0; i < fieldSize; i++) {
                    int fNodeMapsize = formIdNodeIdMap.size();
                    if (fNodeMapsize >0){
                        JSONObject jsonObject = fieldArray.getJSONObject(i);
                        relatedProductHelper.handlerRelProduct(boardJson, formIdNodeIdMap, attrRelationProduct, jsonObject, inputNodeIdSet);
                    }
                }
                Set<Long> keySet = formIdMap.keySet();
                for (Long formId : keySet) {
                    DataSetValueAnalysisPojo dataSetValueAnalysisPojo = formIdMap.get(formId);
                    String relProductAttr = attrRelationProduct.get(formId);
                    int rPsize = attrRelationProduct.size();
                    if (rPsize >0){
                        relatedProductHelper.getNewProduct(chartAnalysisDTO.getCorpid(), tableHead, dataSetValueAnalysisPojo.getBusinessType(), jsonArray,relProductAttr);
                    }
                }
            }

            //统计表
            boolean statisticsTable = Objects.equals(chartEntity.getChartType(), ChartTypeEnum.DATA_STATISTICS_TABLE.getCode());

            // 加入这步处理是因为钻取之后翻页的时候重新划分行列分组时使用的原来的图表，所以需要先处理图表结构
            if (statisticsTable) {
                // 钻取之后需要改变左侧列分组数据，目的是插入钻取的属性值(列分组)
                statisticsTableHelper.dealTableRowOrColAttrDrillSign(DrillFieldEnum.COL_GROUP_ATTR.getAlias(), chartEntity.getColGroupAttr(), diyResultDTO, chartEntity);
                // 钻取之后需要改变左侧行分组数据，目的是插入钻取的属性值(行分组)
                statisticsTableHelper.dealTableRowOrColAttrDrillSign(DrillFieldEnum.ROW_GROUP_ATTR.getAlias(), chartEntity.getRowGroupAttr(), diyResultDTO, chartEntity);
            }

            chartAnalysisDTO.setResultArray(jsonArray);
            chartAnalysisDTO.setPageHelper(pageHelper);
            chartAnalysisDTO.setTableHead(tableHead);
            chartAnalysisDTO.setParseAttrMap(parseAttrMap);
            chartAnalysisDTO.setSummaryAttrMap(generateSqlVO.getSummaryAttrMap());
            chartAnalysisDTO.setSecondTargetKey(generateSqlVO.getSecondTargetKey());
            chartAnalysisDTO.setAggFieldMap(aggFieldMap);
            chartAnalysisDTO.setPageTurn(chartResultPojo.getPageTurn());
            // 渲染
            ChartAnalysisVO chartAnalysisVO = chartTypeStrategyService.chartAnalysis(chartAnalysisDTO);
            JSONObject result = Objects.nonNull(chartAnalysisVO) ? chartAnalysisVO.getResult() : new JSONObject();
            if (Objects.equals(chartEntity.getChartType(), ChartTypeEnum.DATA_QUERY_TABLE.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.PK_CUSTOM.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.DATA_STATISTICS_TABLE.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.TARGET_CHART.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.SECOND_TARGET_CHART.getCode())
            ) {
                ResultTableVO resultTableVO = new ResultTableVO();
                String redisKey = null;
                if(statisticsTable){
                    redisKey =  MD5Util.EncoderByMd5(sql);
                }
                if (result != null && result.size() > 0) {
                    if(statisticsTable){
                        resultTableVO = statisticsTableHelper.statisticsTableConstruction(chartEntity, chartResultPojo, pageHelper, redisKey, result, resultTableVO);
                    }else {
                        resultTableVO = JSON.parseObject(result.toJSONString(), ResultTableVO.class);
                    }
                }
                resultTableVO.setPageHelper(pageHelper);
                resultTableVO.setTableName(chartEntity.getName());
                resultTableVO.setChartType(chartEntity.getChartType());

                // 返回钻取的层级信息
                statisticsTableHelper.dealTableDrillInfo(chartEntity, chartResultPojo, resultTableVO);

                chartResultDetailVO.setTable(resultTableVO);
                if(Objects.equals(chartEntity.getChartType(), ChartTypeEnum.DATA_QUERY_TABLE.getCode())){
                    if (chartEntity.getSummaryAttr() != null && chartEntity.getSummaryAttr().size() > 0) {
//                        boolean penetrateFlag = ckResultHelp.getPenetrateFlag(chartEntity.getFilter());
                        //第一页且非穿透里面才会传出来
                        List<AggsBucketsPojo> aggList = generateSqlVO.getAggList();
                        if(CollectionUtils.isNotEmpty(aggList)){
                            chartResultDetailVO.setAggList(aggList);
                        }
                        /*if(Objects.equals(chartResultPojo.getPage(),1) && !penetrateFlag){
                        }*/
                    }
                    
                }
            }else if (Objects.equals(chartEntity.getChartType(), ChartTypeEnum.BAR_CHART.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.BROADWISE_BAR_CHART.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.LINE_CHART.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.AREA_CHART.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.RADAR_CHART.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.PIE_CHART.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.BIAXIAL_CHART.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.MAP_CUSTOM.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.SCATTER_CHART.getCode())
                    || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.FUNNEL.getCode())) {
                ResultChartVO resultChartVO = new ResultChartVO();
                if (result != null && result.size() > 0) {
                    resultChartVO = JSON.parseObject(result.toJSONString(), ResultChartVO.class);
                }
                List<ResultChartVO> chartVOList = new ArrayList<>();
                chartVOList.add(resultChartVO);
                chartResultDetailVO.setChart(chartVOList);
            }
        }  catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            logger.error("",e);
            throw new XbbException(BiErrorCodeEnum.API_ERROR_241023);
        }
        return chartResultDetailVO;
    }

    /**
     * 获取统计表各象限的数据
     *
     * @param generateSqlVO 组装sql后的响应对象
     * @param chartAnalysisDTO 入参实体
     * @param chartEntity 图表实体
     * @author zyy
     * @date 2022/10/28
     * @version v1.0
     */
    private void statisticsTableTotalResult(GenerateSqlVO generateSqlVO, ChartAnalysisDTO chartAnalysisDTO, ChartEntity chartEntity) throws XbbException {
        try {
            StatisticsSumEnum statisticsSumEnum = StatisticsSumEnum.getEnumBySum(chartEntity.getSum());
            switch (statisticsSumEnum) {
                case SUB_TOTAL:
                    //小计值
                    subTotalResult(chartAnalysisDTO,generateSqlVO);
                    break;
                case ALL:
                    // 总计 & 小计
                    subTotalResult(chartAnalysisDTO,generateSqlVO);
                    sumTotalResult(chartAnalysisDTO,generateSqlVO);
                    break;
                default:
                    //默认总计
                    sumTotalResult(chartAnalysisDTO,generateSqlVO);
                    break;
            }
        }catch(Exception e){
            logger.error("统计表总计、小计数据获取失败，chartId=" + chartEntity.getId(), e);
            throw new XbbException(BiErrorCodeEnum.API_ERROR_241023);
        }
    }

    /**
     * 获取总计数据
     *
     * @param chartAnalysisDTO 解析参数实体
     * @param generateSqlVO 组装sql后的响应对象
     * @author zyy
     * @date 2022/10/28
     * @version v1.0
     */
    private void sumTotalResult(ChartAnalysisDTO chartAnalysisDTO, GenerateSqlVO generateSqlVO) {
        if(StringUtils.isNotBlank(generateSqlVO.getSumTotalSql())){
            chartAnalysisDTO.setSumJsonArray(JSONArray.parseArray(JSON.toJSONString(starDataService.findListMapBySql(generateSqlVO.getSumTotalSql()))));
        }
        if(StringUtils.isNotBlank(generateSqlVO.getSumRightTotalSql())){
            chartAnalysisDTO.setSumRightJsonArray(JSONArray.parseArray(JSON.toJSONString(starDataService.findListMapBySql(generateSqlVO.getSumRightTotalSql()))));
        }
        if(StringUtils.isNotBlank(generateSqlVO.getTotalOfTotalSql())){
            chartAnalysisDTO.setTotalOfTotalJsonArray(JSONArray.parseArray(JSON.toJSONString(starDataService.findListMapBySql(generateSqlVO.getTotalOfTotalSql()))));
        }
    }

    /**
     * 获取小计数据
     *
     * @param chartAnalysisDTO 解析参数实体
     * @param generateSqlVO 组装sql后的响应对象
     * @author zyy
     * @date 2022/10/28
     * @version v1.0
     */
    private void subTotalResult(ChartAnalysisDTO chartAnalysisDTO, GenerateSqlVO generateSqlVO) {
        if(StringUtils.isBlank(generateSqlVO.getSubTotalSql())){
            return;
        }
        chartAnalysisDTO.setSubTotalJsonArray(JSONArray.parseArray(JSON.toJSONString(starDataService.findListMapBySql(generateSqlVO.getSubTotalSql()))));
    }

    @Override
    public SearchDataInConditionVO chartLinkResult(ChartLinkDTO chartLinkDTO) throws XbbException {
        DataSetParseDTO dataSetParseDTO = new DataSetParseDTO();
        dataSetParseDTO.setCorpid(chartLinkDTO.getCorpid());
        dataSetParseDTO.setLoginUser(chartLinkDTO.getLoginUser());
        dataSetParseDTO.setDataSetId(chartLinkDTO.getDataSetId());
        dataSetParseDTO.setPreView(chartLinkDTO.preView);
        dataSetParseDTO.setJsonStr(chartLinkDTO.getJsonStr());
        DataSetResultVO dataSetResultVO = parseSqlService.parseSql(dataSetParseDTO);

        String parseSql = dataSetResultVO.getParseSql();
        String attr = chartLinkDTO.getAttr();
        String colums = attr;
        String linkAttr = chartLinkDTO.getLinkedText();
        boolean link = StringUtil.isNotEmpty(linkAttr);
        if(link){
            colums = colums + "," + linkAttr;
        }
        //TODO  filter  模糊查询的处理
        String filter = "";
        if(chartLinkDTO.getValue() != null && !Objects.equals("",chartLinkDTO.getValue())){
            String fliterAttr = attr;
            if(link){
                fliterAttr = linkAttr;
            }
            filter = XbbConstant.WHERE +  fliterAttr  + XbbConstant.SPACE + XbbConstant.LIKE + "  '%" +chartLinkDTO.getValue()+  "%'";
        }else {
            filter = XbbConstant.WHERE +  attr + " is not null ";
        }
        StringBuffer sql = chartDataSetHelper.tableSqlAppend(parseSql, colums, null, filter, 10, 0, null, false, null);
        List resultList = starDataService.findListMapBySql(sql.toString());
        SearchDataInConditionVO  searchDataInConditionVO = new SearchDataInConditionVO();
        if(CollectionsUtil.isNotEmpty(resultList)){
            List<ItemDataPoJo> items = new ArrayList<>(resultList.size());
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
            for (int i = 0; i < jsonArray.size(); i++) {
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                JSONObject json = jsonArray.getJSONObject(i);
                itemDataPoJo.setValue(json.get(attr));
                if(link){
                    itemDataPoJo.setText(json.get(linkAttr));
                }else {
                    itemDataPoJo.setText(json.get(attr));
                }
                items.add(itemDataPoJo);
            }
            searchDataInConditionVO.setItems(items);
        }
        return searchDataInConditionVO;
    }

}
